package org.example.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author: sql
 * @date: 2024/6/7
 * @Description: 规定成功响应此结果
 * @version: 1.0
 */
@Data
public class R<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = -8621900780393672869L;

    @JsonIgnore
    private final static BaseCodeEnum success = BaseCodeEnum.SUCCESS;
    @JsonIgnore
    private final static BaseCodeEnum error = BaseCodeEnum.SERVICE_EXCEPTION;

    /**
     * 状态码：00000 - 代表此次请求成功, 其他请参考错误代码信息表
     */
    private String code = success.getCode();

    /**
     * 响应信息
     */
    private String msg = success.getMsg();

    /**
     * 响应数据
     */
    private T data;

    private R(T data) {
        this.data = data;
    }

    private R(String msg, T data) {
        this.msg = msg;
        this.data = data;
    }

    private R(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> R<T> ok() {
        return ret((T) null);
    }

    public static <T> R<T> ret(T data) {
        return new R<>(data);
    }

    public static <T> R<T> ret(String msg, T data) {
        return new R<>(msg, data);
    }

    public static <T> R<T> ret(String code, String msg) {
        return ret(code, msg, null);
    }

    public static <T> R<T> ret(String code, String msg, T data) {
        return new R<>(code, msg, data);
    }

    public static <T> R<T> ret(ICodeEnum codeEnum) {
        return ret(codeEnum.getCode(), codeEnum.getMsg());
    }

    public static <T> R<T> error(String msg) {
        return ret(error.getCode(), msg);
    }

    @JsonIgnore
    public boolean isSuccessful() {
        return success.getCode().equals(this.code);
    }

    @JsonIgnore
    public boolean isError() {
        return !this.isSuccessful();
    }
}
